// @author: caoshi
// @date: 2021-05-14 20:01
// 测试json数据传递, 顺带复习一下jQuery的Ajax

package main

import (
	"demo05_json_params/src/test"
	"encoding/json"
	"fmt"
	"html/template"
	"net/http"
)

func index(w http.ResponseWriter, r *http.Request)  {
	temp, _ := template.ParseFiles("view/index.html")
	temp.Execute(w, nil)
}


// 处理展示用户信息的请求
func showInfo(w http.ResponseWriter, r *http.Request) {
	//fmt.Println(1223)
	userList := make([]test.User, 0)
	userList = append(userList, test.User{"张三", 18, "湖北武汉", "王者荣耀"})
	userList = append(userList, test.User{"李四", 19, "北京朝阳", "吃鸡"})
	userList = append(userList, test.User{"Mary", 21, "美国纽约", "登山"})
	userList = append(userList, test.User{"王五", 17, "河南郑州", "游泳"})
	b, _ := json.Marshal(userList)
	userJsonStr := string(b)
	// 设置响应头信息
	// 注意: 在这里设置了响应数据是json对象, 所以在前端页面中就不需要再次
	// 使用 JSON.parse() 进行解析了, resp 直接就是一个json对象
	w.Header().Set("Content-Type", "application/json;charset=utf-8")
	fmt.Fprintln(w, userJsonStr)
}

func main() {
	server := http.Server{Addr: ":8090"}
	// 处理静态资源文件
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	http.HandleFunc("/", index)
	http.HandleFunc("/showinfo", showInfo)
	server.ListenAndServe()
}

